import 'package:flutter/material.dart';
import 'dart:math';
import '../models/morse_character.dart';
import '../services/morse_audio_service.dart';

class SequencePracticePage extends StatefulWidget {
  const SequencePracticePage({super.key});

  @override
  State<SequencePracticePage> createState() => _SequencePracticePageState();
}

class _SequencePracticePageState extends State<SequencePracticePage> {
  final MorseAudioService _audioService = MorseAudioService();
  final Random _random = Random();
  final TextEditingController _textController = TextEditingController();
  final FocusNode _focusNode = FocusNode();
  
  bool isLoading = false;
  bool hasSubmitted = false;
  bool isCorrect = false;
  int score = 0;
  int totalQuestions = 0;
  int currentLength = 2; // 开始时序列长度为2
  
  List<MorseCharacter> currentSequence = [];
  String correctAnswer = '';

  @override
  void initState() {
    super.initState();
    _generateNewSequence();
  }

  @override
  void dispose() {
    _audioService.stop();
    _textController.dispose();
    _focusNode.dispose();
    super.dispose();
  }

  void _generateNewSequence() {
    setState(() {
      hasSubmitted = false;
      isCorrect = false;
      isLoading = false;
    });

    _textController.clear();
    
    // 生成随机长度的序列（2-5个字符）
    final sequenceLength = currentLength;
    currentSequence = [];
    correctAnswer = '';
    
    for (int i = 0; i < sequenceLength; i++) {
      final character = MorseData.letters[_random.nextInt(MorseData.letters.length)];
      currentSequence.add(character);
      correctAnswer += character.character;
    }
    
    // 自动播放序列
    Future.delayed(const Duration(milliseconds: 500), () {
      _playSequence();
    });
  }

  Future<void> _playSequence() async {
    if (_audioService.isPlaying || hasSubmitted) return;
    
    setState(() {
      isLoading = true;
    });
    
    try {
      await _audioService.playSequence(currentSequence);
    } finally {
      if (mounted) {
        setState(() {
          isLoading = false;
        });
      }
    }
  }

  void _submitAnswer() {
    if (hasSubmitted || _textController.text.trim().isEmpty) return;
    
    final userAnswer = _textController.text.trim().toUpperCase();
    
    setState(() {
      hasSubmitted = true;
      isCorrect = userAnswer == correctAnswer;
      totalQuestions++;
      
      if (isCorrect) {
        score++;
        // 正确答案增加难度
        if (score % 3 == 0 && currentLength < 5) {
          currentLength++;
        }
      }
    });

    // 显示结果后自动进入下一题
    Future.delayed(const Duration(milliseconds: 2000), () {
      if (mounted) {
        _generateNewSequence();
      }
    });
  }

  void _skipQuestion() {
    setState(() {
      totalQuestions++;
    });
    _generateNewSequence();
  }

  Widget _buildCharacterChip(String character, bool isRevealed) {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 4),
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
      decoration: BoxDecoration(
        color: isRevealed 
            ? (isCorrect ? const Color(0xFF2E7D32) : const Color(0xFFC62828))
            : const Color(0xFF1E1E1E),
        borderRadius: BorderRadius.circular(8),
        border: Border.all(
          color: isRevealed 
              ? (isCorrect ? const Color(0xFF4CAF50) : const Color(0xFFF44336))
              : const Color(0xFF333333),
          width: 1,
        ),
      ),
      child: Text(
        character,
        style: const TextStyle(
          color: Colors.white,
          fontSize: 18,
          fontWeight: FontWeight.bold,
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: const Color(0xFF121212),
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: Colors.white),
          onPressed: () => Navigator.pop(context),
        ),
        title: const Text(
          'Sequence Decoding',
          style: TextStyle(color: Colors.white),
        ),
        actions: [
          Container(
            margin: const EdgeInsets.only(right: 16),
            padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
            decoration: BoxDecoration(
              color: const Color(0xFF1E1E1E),
              borderRadius: BorderRadius.circular(8),
            ),
            child: Text(
              '$score/$totalQuestions',
              style: const TextStyle(
                color: Color(0xFF00BFFF),
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
        ],
      ),
      body: SafeArea(
        child: Padding(
          padding: const EdgeInsets.all(20.0),
          child: Column(
            children: [
              // Header
              Column(
                children: [
                  Text(
                    'Sequence Length: $currentLength',
                    style: const TextStyle(
                      fontSize: 16,
                      color: Color(0xFFAAAAAA),
                    ),
                  ),
                  const SizedBox(height: 5),
                  const Text(
                    'Listen and type the letters',
                    style: TextStyle(
                      fontSize: 24,
                      fontWeight: FontWeight.bold,
                      color: Colors.white,
                    ),
                  ),
                ],
              ),
              
              const SizedBox(height: 30),
              
              // Score progress
              if (totalQuestions > 0)
                Container(
                  padding: const EdgeInsets.all(16),
                  decoration: BoxDecoration(
                    color: const Color(0xFF1E1E1E),
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        'Accuracy: ${totalQuestions > 0 ? ((score / totalQuestions) * 100).toStringAsFixed(0) : '0'}%',
                        style: const TextStyle(
                          color: Colors.white,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      Text(
                        'Level: ${currentLength - 1}',
                        style: const TextStyle(
                          color: Color(0xFF00BFFF),
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ],
                  ),
                ),
              
              const SizedBox(height: 40),
              
              // Audio Player
              GestureDetector(
                onTap: _playSequence,
                child: Container(
                  width: 120,
                  height: 120,
                  decoration: BoxDecoration(
                    color: const Color(0xFF1E1E1E),
                    border: Border.all(
                      color: isLoading ? const Color(0xFFFFB74D) : const Color(0xFF00BFFF),
                      width: 3,
                    ),
                    shape: BoxShape.circle,
                  ),
                  child: isLoading
                      ? const CircularProgressIndicator(
                          color: Color(0xFFFFB74D),
                        )
                      : Icon(
                          _audioService.isPlaying ? Icons.volume_up : Icons.replay,
                          size: 48,
                          color: const Color(0xFF00BFFF),
                        ),
                ),
              ),
              
              const SizedBox(height: 20),
              
              Text(
                'Tap to ${_audioService.isPlaying ? 'listen' : 'replay'} sequence',
                style: const TextStyle(
                  color: Color(0xFFAAAAAA),
                  fontSize: 14,
                ),
              ),
              
              const SizedBox(height: 40),
              
              // Answer display (if answered)
              if (hasSubmitted)
                Column(
                  children: [
                    const Text(
                      'Correct Answer:',
                      style: TextStyle(
                        color: Color(0xFFAAAAAA),
                        fontSize: 16,
                      ),
                    ),
                    const SizedBox(height: 8),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: correctAnswer.split('').map((char) {
                        return _buildCharacterChip(char, true);
                      }).toList(),
                    ),
                    const SizedBox(height: 20),
                    Container(
                      padding: const EdgeInsets.all(16),
                      decoration: BoxDecoration(
                        color: isCorrect ? const Color(0xFF2E7D32) : const Color(0xFFC62828),
                        borderRadius: BorderRadius.circular(12),
                      ),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Icon(
                            isCorrect ? Icons.check_circle : Icons.cancel,
                            color: Colors.white,
                            size: 24,
                          ),
                          const SizedBox(width: 8),
                          Text(
                            isCorrect ? 'Correct!' : 'Try again next time',
                            style: const TextStyle(
                              color: Colors.white,
                              fontSize: 16,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              
              const SizedBox(height: 40),
              
              // Input field
              if (!hasSubmitted) ...[
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 16),
                  decoration: BoxDecoration(
                    color: const Color(0xFF1E1E1E),
                    borderRadius: BorderRadius.circular(12),
                    border: Border.all(
                      color: const Color(0xFF333333),
                      width: 1,
                    ),
                  ),
                  child: TextField(
                    controller: _textController,
                    focusNode: _focusNode,
                    style: const TextStyle(
                      color: Colors.white,
                      fontSize: 18,
                      letterSpacing: 4,
                    ),
                    textAlign: TextAlign.center,
                    textCapitalization: TextCapitalization.characters,
                    decoration: const InputDecoration(
                      hintText: 'Type the letters...',
                      hintStyle: TextStyle(
                        color: Color(0xFFAAAAAA),
                        letterSpacing: 2,
                      ),
                      border: InputBorder.none,
                      contentPadding: EdgeInsets.symmetric(vertical: 16),
                    ),
                    onSubmitted: (_) => _submitAnswer(),
                  ),
                ),
                
                const SizedBox(height: 20),
                
                Row(
                  children: [
                    Expanded(
                      child: ElevatedButton(
                        onPressed: _submitAnswer,
                        style: ElevatedButton.styleFrom(
                          backgroundColor: const Color(0xFF00BFFF),
                          foregroundColor: Colors.white,
                          padding: const EdgeInsets.symmetric(vertical: 16),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(12),
                          ),
                        ),
                        child: const Text(
                          'Submit',
                          style: TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                    ),
                    const SizedBox(width: 16),
                    ElevatedButton(
                      onPressed: _skipQuestion,
                      style: ElevatedButton.styleFrom(
                        backgroundColor: const Color(0xFF1E1E1E),
                        foregroundColor: const Color(0xFFAAAAAA),
                        padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 16),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12),
                        ),
                      ),
                      child: const Text('Skip'),
                    ),
                  ],
                ),
              ],
              
              if (hasSubmitted) ...[
                ElevatedButton(
                  onPressed: _generateNewSequence,
                  style: ElevatedButton.styleFrom(
                    backgroundColor: const Color(0xFF00BFFF),
                    foregroundColor: Colors.white,
                    padding: const EdgeInsets.symmetric(horizontal: 40, vertical: 16),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(12),
                    ),
                  ),
                  child: const Text(
                    'Next Sequence',
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
              ],
              
              const Spacer(),
              
              // Hint
              if (!hasSubmitted)
                Container(
                  padding: const EdgeInsets.all(16),
                  decoration: BoxDecoration(
                    color: const Color(0xFF1E1E1E),
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: Column(
                    children: [
                      const Row(
                        children: [
                          Icon(
                            Icons.lightbulb_outline,
                            color: Color(0xFF00BFFF),
                            size: 20,
                          ),
                          SizedBox(width: 8),
                          Text(
                            'Tip:',
                            style: TextStyle(
                              color: Color(0xFF00BFFF),
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ],
                      ),
                      const SizedBox(height: 8),
                      Text(
                        'Listen carefully to the gaps between characters. You can replay the sequence as many times as needed.',
                        style: const TextStyle(
                          color: Color(0xFFAAAAAA),
                          fontSize: 14,
                        ),
                      ),
                    ],
                  ),
                ),
            ],
          ),
        ),
      ),
    );
  }
}
